//
//  PullToRefresh.swift
//  Swift-30-demo
//
//  Created by apple on 2021/11/26.
//

import UIKit

class PullToRefresh: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var dataSource = Array<Date>()
    let refresh = UIRefreshControl()
    var dataTable : UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "PullToRefresh"
        self.view.backgroundColor = UIColor.white
        // Do any additional setup after loading the view.
        createMainView()
    }
    
    func createMainView() {
        dataTable = UITableView(frame: self.view.bounds)
        dataTable.frame.origin.y = 44
        dataTable.delegate = self
        dataTable.dataSource = self
        self.view.addSubview(dataTable)
        
        addNewElementToArray()
        refresh.attributedTitle = NSAttributedString(string: "拉什么拉！？再拉朕就要碎了")
        refresh.addTarget(self, action: #selector(pullTheRefresh), for: .valueChanged)
        dataTable.addSubview(refresh)
        dataTable.reloadData()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "reuseCellForPullToRefresh")
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy年MM月dd日/HH时mm分ss秒"
        let dateStr = dateFormatter.string(from: dataSource[indexPath.row])
        cell.textLabel?.text = dateStr
        return cell
    }

    func addNewElementToArray() {
        dataSource.insert(NSDate() as Date, at: 0)
    }
    
    @objc func pullTheRefresh() {
        addNewElementToArray()
        refresh.endRefreshing()
        dataTable.reloadData()
    }
}
